import {Util,Dialog} from '@lowcode/jpaas-common-lib';
import FormCodegenVariableApi from "@/api/form/codegen/formCodegenVariable";
import FormCodegenTemplateApi from "@/api/form/codegen/formCodegenTemplate";
import codegenTemplateType from "@/views/modules/form/codegen/codegenTemplateType";

export default {
    props: ["formData"],
    mixins:[codegenTemplateType],
    data(){
        return{
            panelActiveKeys:["globalVars"],
            settingJson:{},
            labelCol: { span:6 },
            wrapperCol: { span:18 },
            labelCol1: { span:3 },
            wrapperCol1: { span:19 },
            vars:[],
            //全局变量
            globalVars:{},
            //自定义变量
            customVars:[],
            varsColumns:[
                {title: this.i18n('varsColumns.name','变量名'), dataIndex: 'name', width: 130, scopedSlots: {customRender: 'name'}},
                {title: this.i18n('varsColumns.value','变量值'), dataIndex: 'value', width: 130, scopedSlots: {customRender: 'value'}},
                {title: this.i18n('varsColumns.desc','变量备注'), dataIndex: 'desc', width: 130, scopedSlots: {customRender: 'desc'}}
            ],
            //生成文件
            files:[],
            fileColumns: [
                {title: this.i18n('fileColumns.isGen','是否生成'),dataIndex: 'isGen', width: 50,type: 'checkboxColumn',align:'center', scopedSlots: {customRender: 'isGen'}},
                {title: this.i18n('fileColumns.isOverride','是否覆盖'),dataIndex: 'isOverride', width: 50,type: 'checkboxColumn',align:'center', scopedSlots: {customRender: 'isOverride'}},
                {title: this.i18n('fileColumns.isSub','主从分离'),dataIndex: 'isSub', width: 50,type: 'checkboxColumn',align:'center', scopedSlots: {customRender: 'isSub'}},
                {title: this.i18n('fileColumns.templateType','模板类型'),dataIndex: 'templateType', width: 100,displayField:'templateTypeName', scopedSlots: {customRender: 'templateType'}},
                {title: this.i18n('fileColumns.templateFile','模板文件'),dataIndex: 'templateFile', width: 130, scopedSlots: {customRender: 'templateFile'}},
                {title: this.$ti18('rxList.action','操作'),dataIndex: 'action', width: 50, scopedSlots: {customRender: 'action'}}
            ],
            //模板类型文件
            templateTypeFiles:{}
        }
    },
    computed: {
        arrLen() {
            let len = Math.ceil(this.vars.length / 2);
            if (len == 0) {
                len = len + 1
            }
            return len
        }
    },
    created(){
        this.init();
    },
    methods:{
        i18n(name,text,key){
            return this.$ti18(name,text,"formCodegenBusiness",key);
        },
        init(){
            this.settingJson=JSON.parse(this.formData.settingJson);
            if(this.settingJson.hasOwnProperty("customVars") && this.settingJson.customVars.length>0){
                this.customVars=Util.deepClone(this.settingJson.customVars);
            }
            var self=this;
            this.initGlobalVars(function(vars){
                self.vars = vars;
                var globalVars={};
                if(self.settingJson.hasOwnProperty("globalVars")){
                    globalVars=Util.deepClone(self.settingJson.globalVars);
                }
                for(var i=0;i<vars.length;i++){
                    var obj=vars[i];
                    self.$set(self.globalVars,obj.name,globalVars[obj.name] || obj.value);
                }
            });
        },
        initTemplateFile() {
            this.settingJson = JSON.parse(this.formData.settingJson);
            var templateTypeObj = {};
            if (this.settingJson.hasOwnProperty("files")) {
                let files = this.settingJson.files;
                files.forEach(item => {
                    templateTypeObj[item.templateType] = {
                        templateType: item.templateType,
                        templateTypeName: item.templateTypeName,
                        isSub: item.isSub,
                        isFront: item.isFront,
                        templateFile: item.templateFile,
                        templateContent: item.templateContent,
                        isGen: item.isGen,
                        isOverride: item.isOverride
                    };
                })
            }
            this.templateTypeList.forEach(item => {
                let file = {
                    templateType: item.value,
                    templateTypeName: item.label,
                    isSub: true,
                    isFront: item.isFront,
                    templateFile: "",
                    templateContent: "",
                    isGen: true,
                    isOverride: true
                };
                if (templateTypeObj.hasOwnProperty(item.value)) {
                    file = templateTypeObj[item.value];
                }
                this.loadTemplateFile(item.value, file);
                this.files.push(file);
            })
        },
        loadTemplateFile(templateType,file){
            var self=this;
            FormCodegenTemplateApi.getByTemplateType(templateType).then(res=>{
                if(res.success && res.data && res.data.length>0) {
                    let template = res.data[0];
                    if(!file.templateFile) {
                        file.templateFile = template.id;
                        file.templateContent = template.content;
                    }else{
                        let templateIdAry=res.data.map(item=>{
                            return item.id;
                        });
                        if(!templateIdAry.includes(file.templateFile)){
                            file.templateFile="";
                            file.templateContent="";
                        }
                    }
                    self.templateTypeFiles[templateType] = res.data.map(item => {
                        return {value: item.id, label: item.name, content: item.content};
                    });
                }
            })
        },
        addCustom(){
            this.customVars.push({name:'',value:'',desc:''})
        },
        removeCustom(){
            this.$refs.customVar.removeSelected();
        },
        changeFile(value,record){
            var ary=this.templateTypeFiles[record.templateType];
            for(var i=0;i<ary.length;i++){
                if(value==ary[i].value){
                    record.templateContent=ary[i].content;
                    return;
                }
            }
        },
        reloadFile(record) {
            var self = this;
            this.$confirm({
                title: this.$ti18('rxMsa.tipsInfo','提示信息'),
                content: this.i18n('msg.restoreTip','确认要还原当前模板内容吗？'),
                okText: this.$ti18('rxForm.ackBtn','确认'),
                cancelText: this.$ti18('rxForm.cancelBtn','取消'),
                zIndex:10000,
                onOk() {
                    FormCodegenTemplateApi.get(record.templateFile).then(res => {
                        if (res.success) {
                            record.templateContent = res.data.content;
                            self.$message.success(this.i18n('msg.reloadSuccess','模板内容还原成功！'));
                        }
                    })
                },
                onCancel() {
                }
            })
        },
        editFile(record){
            let scriptInsertAry=[];
            let formAry={name: this.i18n('formVar','表单变量'),children:[
                {name:this.i18n('classVarName','类变量名'),clickEvent:"${model.vars.classVar}"},
                {name:this.i18n('className','类名'),clickEvent:"${model.vars.class}"},
                {name:this.i18n('package','包名'),clickEvent:"${model.vars.package}"},
                {name:this.i18n('packageName','子系统名称'),clickEvent:"${model.vars.packageName}"}
            ]};
            let globalAry={name:this.i18n('globalVars','全局变量'),children:[]};
            globalAry.children=this.vars.map(item=>{
                return {name:item.desc || item.name,clickEvent:"${vars."+item.name+"}"};
            })
            let customAry={name:this.i18n('customVar','自定义变量'),children:[]};
            let customVars=this.customVars.filter(item=>{return item.name && item.value});
            customAry.children=customVars.map(item=>{
                return {name:item.desc || item.name,clickEvent:"${vars."+item.name+"}"};
            })
            scriptInsertAry.push(formAry);
            scriptInsertAry.push(globalAry);
            scriptInsertAry.push(customAry);

            Dialog.openScripttextDialog({
                curVm: this, widthHeight: ['1200px', '600px'], data: {script: record.templateContent,scriptInsertAry:scriptInsertAry}
            }, function (self, data) {
                record.templateContent = data;
            })
        },
        getData(){
            //自定义变量排除空数据
            let customVars=this.customVars.filter(item=>{return item.name && item.value});
            let data={globalVars:this.globalVars,customVars:customVars,files:this.files};
            let result={success:true,data:data};
            for(let i=0;i<customVars.length;i++){
                if(this.globalVars.hasOwnProperty(customVars[i].name)){
                    result.success=false;
                    result.message=this.i18n('customVar','自定义变量')+"("+customVars[i].name+")"+this.i18n('msg.repVar','在全局变量中已存在！');
                    return result;
                }
            }
            //是否有至少一个文件生成
            let fileExist=false;
            for(let i=0;i<this.files.length;i++){
                let file=this.files[i];
                if(!file.isGen){
                    //不生成文件不进行校验
                    continue;
                }
                fileExist=true;
                if(!file.templateFile){
                    result.success=false;
                    result.message=this.i18n('fileColumns.templateType','模板类型')+"("+file.templateTypeName+")"+this.i18n('msg.noTemplateFile','未配置模板文件！');
                    return result;
                }
            }
            if(!fileExist){
                result.success=false;
                result.message=this.i18n('msg.leastOne','请选择至少一个生成文件！');
                return result;
            }
            return result;
        },
        initGlobalVars(callback){
            FormCodegenVariableApi.getAllVars().then(res=>{
                if(res.success) {
                    callback(res.data);
                }
            })
        }
    }
}